<template>
	<view class="form-container">
		<view class="input-group">
			<image class="avatar" src="../../static/img/Grua.jpg"></image>
			<uni-forms labelPosition="left" :model="formData">
				<uni-forms-item label="姓名" name="realname">
					<uni-easyinput v-model="formData.realname" placeholder="请输入姓名"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="联系电话" name="phone">
					<uni-easyinput v-model="formData.phone" placeholder="请输入联系电话"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="学号" name="stunum">
					<uni-easyinput v-model="formData.stunum" placeholder="请输入学号"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="宿舍号" name="dormmun">
					<uni-easyinput v-model="formData.dormmun" placeholder="请输入宿舍号"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="button-container">
			<button class="save-button" @click="saveInfo">保存信息</button>
		</view>
	</view>
</template>

<script>
	import '../../common/css/user-info.scss'
	import API from '../../api/api';
	export default {
		data() {
			return {
				formData: {
					realname: '',
					stunum: '',
					phone: '',
					dormmun: ''
				},
				errors: {
					realname: '',
					stunum: '',
					phone: '',
					dormmun: ''
				}
			}
		},
		methods: {
			clearErrors() {
				this.errors = {
					realname: '',
					stunum: '',
					phone: '',
					dormmun: ''
				};
			},
			async saveInfo() {
				this.clearErrors()
				let valid = true
				const phonePattern = /^1[3-9]\d{9}$/;
				if (!this.formData.phone) {
					this.errors.phone = '请输入手机号';
					valid = false;
				} else if (!phonePattern.test(this.formData.phone)) {
					this.errors.phone = '手机号格式不正确';
					valid = false;
				}
				let token = uni.getStorageSync("token")
				let realname = this.formData.realname
				let studentId = this.formData.stunum
				let phone = this.formData.phone
				let dormId = this.formData.dormmun

				let res = API.UpdateUserInfo(token, realname, dormId, phone, studentId)
				console.log(res)
				if (res.code === 1) {
					uni.showToast({
						title: '修改成功',
						icon: 'success',
						duration: 500
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}, 500)
				} else {
					uni.showToast({
						title: '请填写完整的表单',
						icon: 'none'
					});
				}
			},
			async getUserInfo() {
				let token = uni.getStorageSync("token")
				let res = await API.getUserInfo(token)
				this.formData = res.data
			}
		},
		onLoad() {
			this.getUserInfo()
		}
	}
</script>

<style>

</style>